from django.db import models
from django.db.models.manager import Manager
from django.db.models import CharField, AutoField, SmallIntegerField, ForeignKey, OneToOneField


# Create your models here.


class User(models.Model):
    class Meta:
        db_table = 'user'

    id = AutoField(primary_key=True)
    name = CharField(null=False, unique=True, max_length=20)
    email = CharField(null=False, unique=True, max_length=30)
    password = CharField(null=False, max_length=128)
    is_active = SmallIntegerField(default=0)
    is_logout = SmallIntegerField(default=0)
    log_ip = CharField(null=False, unique=True, max_length=15, default="0.0.0.0")

    def __repr__(self):
        return "< User {} {} {} >".format(self.id, self.name, self.email)

    __str__ = __repr__


class Authority(models.Model):
    class Meta:
        db_table = "authority"

    id = AutoField(primary_key=True)
    auth_id = SmallIntegerField(null=False, default=0)
    auth_name = CharField(null=False, max_length=100)

    def __repr__(self):
        return "< Authority {} {} >".format(self.auth_id, self.auth_name)

    __str__ = __repr__


class AuthUser(models.Model):
    class Meta:
        db_table = "user_auth"

    id = AutoField(primary_key=True)
    user_id = ForeignKey('user.user', on_delete=models.DO_NOTHING)
    user_auth = ForeignKey('user.Authority', on_delete=models.DO_NOTHING)

    def __repr__(self):
        return "< AuthUser {} {} >".format(self.user_id, self.user_auth)

    __str__ = __repr__


class GroupAuth(models.Model):
    class Meta:
        db_table = "group_authority"

    id = AutoField(primary_key=True)
    group_id = SmallIntegerField(null=False, default=0)
    group_name = CharField(null=False, max_length=100)
    auth_id = OneToOneField('authority', on_delete=models.DO_NOTHING)

    def __repr__(self):
        return "< GroupAuth {} {} >".format(self.group_id, self.group_name)

    __str__ = __repr__


class GroupUser(models.Model):
    class Meta:
        db_table = "group_user"

    id = AutoField(primary_key=True)
    group_id = ForeignKey('user.GroupAuth', on_delete=models.DO_NOTHING)
    user_id = ForeignKey('user.user', on_delete=models.DO_NOTHING)

    def __repr__(self):
        return "< GroupUser {} {} >".format(self.group_id, self.user_id)

    __str__ = __repr__


class IP(models.Model):
    class Meta:
        db_table = "ip_table"

    id = AutoField(primary_key=True)
    ip = CharField(null=False, max_length=15, unique=True)

    def __repr__(self):
        return "< IP {} >".format(self.ip)

    __str__ = __repr__


user_manger: Manager = getattr(User, 'objects')
authority_manger: Manager = getattr(Authority, 'objects')
auth_user_manger: Manager = getattr(AuthUser, 'objects')
group_auth_manger: Manager = getattr(GroupAuth, 'objects')
group_user_manger: Manager = getattr(GroupUser, 'objects')
ip_manger: Manager = getattr(IP, 'objects')
